/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年4月13日
 * @version 0.1
 */
package com.suredy.base.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.suredy.base.model.Resource;
import com.suredy.core.service.BaseSrvWithEntity;

/**
 * @author ZhangMaoren
 *
 */
@Service("ResourceSrv")
public class ResourceSrv extends BaseSrvWithEntity<Resource> {

	public List<Resource> getAll() {
		return this.readByEntity(null);
	}

	public Resource getById(Long resourceId) {
		return super.get(resourceId);
	}

	public Resource getByUrl(String url) {
		String sql = "SELECT ID, PARENTID, NAME, URL, TYPE, CREATETIME, LASTMODIFIEDTIME, AVAILABLE FROM T_SECURITY_RESOURCE WHERE URL=?";
		Resource res = super.readSingleBySQL(sql, Resource.class, url);
		return res;
	}

	public void add(Resource resource) {
		this.saveOrUpdate(resource);
	}

	public void update(Resource resource) {
		this.update(resource);
	}

	public void remove(Resource resource) {
		this.delete(resource);
	}

	public List<Resource> getJuniors(Long parentId) {
		List<Resource> ret = new ArrayList<Resource>();
		List<Resource> sub = getChildren(parentId);
		for (Resource r : sub) {
			ret.add(r);
			ret.addAll(getChildren(r.getId()));
		}
		return ret;

	}

	public List<Resource> getChildren(Long parentId) {
		String sql = "SELECT ID, PARENTID, NAME, URL, TYPE, CREATETIME, LASTMODIFIEDTIME, AVAILABLE FROM T_SECURITY_RESOURCE WHERE PARENTID=?";
		List<Resource> children = super.readBySQL(sql, Resource.class, parentId);
		return children;
	}

}
